'use strict';

const Service = require('egg').Service;

class NewsService extends Service {
  async list() {
    // read config
    const { serverUrl } = this.config.news;

    // use build-in http client to GET hacker-news api
    const data = await this.ctx.curl(
      `${serverUrl}/topstories`,
      {
        // data: {
        //   orderBy: '"$key"',
        //   startAt: `"${pageSize * (page - 1)}"`,
        //   endAt: `"${pageSize * page - 1}"`,
        // },
        dataType: 'json',
      }
    );

    // await console.log('result is ' +JSON.stringify(data.data));

    // parallel GET detail
    const newsList = await Promise.all(
      // Object.keys(idList).map((key) => {
      // const url = `${serverUrl}/item/${idList[key]}.json`;
      // console.log('result is ' +JSON.stringify(data.data));
      data.data.map(element => {
        const url = `${serverUrl}/${element}`;
        return this.ctx.curl(url, { dataType: 'json' });
      })
    );

    return newsList.map(res => res.data);
  }
}

module.exports = NewsService;
